package juc.aqs;

import java.util.concurrent.locks.StampedLock;

/*
* stampedlock 读写锁改进
* 特点：在读读并发时不维护任何变量和队列 性能高
* 缺点：不支持读到写的重入 也不支持条件变量
* */
public class Test3 {
    public static void main(String[] args) throws InterruptedException {
        DataContainerStamp stampedlock = new DataContainerStamp("stampedlock");
        new Thread(()->{
            stampedlock.write("data");
        }).start();
           new Thread(()->{
            stampedlock.read();
        }).start();
        Thread.sleep(500);
        new Thread(()->{
            stampedlock.read();
        }).start();
        Thread.sleep(500);
        new Thread(()->{
            stampedlock.read();
        }).start();

//        Thread.sleep(500);

    }
}
class DataContainerStamp{
     private Object data;
     private StampedLock stampedLock=new StampedLock();

    public DataContainerStamp(Object data) {
        this.data = data;
    }

    public Object read(){
        long stamp = stampedLock.tryOptimisticRead();
        if(stampedLock.validate(stamp)){
            System.out.println("乐观读...");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return data;
        }
        System.out.println("乐观读锁升级为读锁...");
        stamp = stampedLock.readLock();
        try {
            System.out.println("读取");

            return data;
        } finally {
            stampedLock.unlockRead(stamp);
        }
    }
    public void write(Object data){
        long stamp = stampedLock.writeLock();
        try {
            System.out.println("写数据");
            Thread.sleep(3000);
            this.data=data;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            stampedLock.unlockWrite(stamp);
        }
    }
}
